import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_yishop/config/Config.dart';
import 'package:flutter_yishop/constants/Constants.dart';
import 'package:flutter_yishop/res/sub_header_list.dart';
import 'package:flutter_yishop/services/SearchServices.dart';
import '../../utils/screen/ScreenAdapter.dart';
import 'package:dio/dio.dart';
import '../../model/HotProductsModel.dart';
import '../../widget/LoadingWidget.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class Product extends StatefulWidget {
  Map arguments;

  Product({this.arguments});

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _Product();
  }
}

class _Product extends State<Product> {
  final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();

  //用于上拉分页
  ScrollController _scrollController = ScrollController(); //listview 的控制器

  RefreshController _refreshController =
      RefreshController(initialRefresh: false);

  //是否加载过数据
  bool loaded;

  var productList;

  //分页
  int _page = 1;

  //判断有没有数据f
  bool hasMore = true;

  //数据
  List _productList = [];

  //是否显示loading
  bool _showLoading = false;

  //排序
  //价格升序 sort=price_1 价格降序 sort=price_-1 销量升序 sort=salecount_1 销量降序 sort=salecount_-1
  String _sort = '';

  int _selectHeaderId = 1;

  bool isSalesDown = true;
  bool isPriceDown = true;

  //配置搜索框的controller
  TextEditingController _initKeywordsController = TextEditingController();
  String _keyWords;
  bool _isShowSearchAppBar = false;

  @override
  void initState() {
    widget.arguments['keyWords']==null?_isShowSearchAppBar=false:_isShowSearchAppBar=true;
    widget.arguments['keyWords']==null?_initKeywordsController.text ="":_initKeywordsController.text = widget.arguments['keyWords'];

    _loadData(true);
  }

  void _onRefresh() async {
    _loadData(true);
  }

  void _onLoading() async {
    if (hasMore) {
      _loadData(false);
    }
  }

  _loadData(final bool onRefresh) async {
    if (onRefresh) {
      this.hasMore = true;
      _page = 1;
    } else {
      _page = _page + 1;
    }
    _showLoading = true;

    var api;
    if(widget.arguments['keyWords']==null){//分类
      api =
      '${Config.url}api/plist?cid=${widget.arguments['cid']}&page=${_page}&sort=${this._sort}';
    }else{//搜索
      api =
      '${Config.url}api/plist?search=${widget.arguments['keyWords']}&page=${_page}&sort=${this._sort}';
    }

    print(api);
    var reult = await Dio().get(api);
    productList = new HotProductsModel.fromJson(reult.data);
    _showLoading = false;
    if (onRefresh) {
      loaded = true;
      this._productList.clear();
      setState(() {
        this._productList.addAll(productList.result);
      });

      _refreshController.refreshCompleted();
    } else {
      setState(() {
        this._productList.addAll(productList.result);
      });

      _refreshController.loadComplete();
    }
    //隐藏键盘
    FocusScope.of(context).requestFocus(FocusNode());
  }

  //商品列表
  Widget _productListWidget(value) {
    if (_showLoading) {
      return LoadingWidget();
    } else {
      if (value.length > 0) {
        hasMore = true;
        return Container(
          padding: EdgeInsets.all(10),
          margin: EdgeInsets.only(top: ScreenAdapter.height(80)),
          child: SmartRefresher(
            enablePullDown: true,
            enablePullUp: true,
            header: ClassicHeader(),
            footer: CustomFooter(
              builder: (BuildContext context, LoadStatus mode) {
                Widget body;
                if (this.productList.result != null &&
                    this.productList.result.length > 0) {
                  if (this.productList.result.length < 9) {
                    mode == LoadStatus.noMore;
                  }

                  if (mode == LoadStatus.idle) {
                    body = Text("上拉加载");
                  } else if (mode == LoadStatus.loading) {
                    body = CupertinoActivityIndicator();
                  } else if (mode == LoadStatus.failed) {
                    body = Text("加载失败！点击重试！");
                  } else if (mode == LoadStatus.canLoading) {
                    body = Text("松手,加载更多!");
                  }
                } else {
                  hasMore = false;
                  body = Text("没有更多数据了!");
                }
                return Container(
                  height: 55.0,
                  child: Center(child: body),
                );
              },
            ),
            controller: _refreshController,
            onRefresh: _onRefresh,
            onLoading: _onLoading,
            child: ListView.builder(
                controller: _scrollController,
                itemCount: value.length,
                itemBuilder: (context, index) {
                  //图片
                  String sPic = value[index].pic;
                  sPic = Config.url + sPic.replaceAll('\\', '/');
                  return _productItemWiget(sPic, index, value);
                }),
          ),
        );
      } else {
        hasMore = false;
        return Center(
          child: Text("没有数据"),
        );
      }
    }
    // return LoadingWidget();
  }

  //ItemWidget
  Widget _productItemWiget(sPic,index,value){
    return  InkWell(
      child: Column(
        children: <Widget>[
          Row(
            children: <Widget>[
              Container(
                width: ScreenAdapter.width(180),
                height: ScreenAdapter.height(180),
                child: Image.network(
                  "${sPic}",
                  fit: BoxFit.cover,
                ),
              ),
              Expanded(
                  flex: 1,
                  child: Container(
                    height: ScreenAdapter.height(180),
                    margin: EdgeInsets.all(ScreenAdapter.width(15)),
                    child: Column(
                      mainAxisAlignment:
                      MainAxisAlignment.spaceBetween,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        Text(
                          "${value[index].title}",
                          maxLines: 2,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(),
                        ),
                        // Row(
                        //   children: <Widget>[_getRadiusText("256g")],
                        // ),
                        Text(
                          "￥${value[index].price}",
                          style: TextStyle(color: Colors.redAccent),
                        ),
                      ],
                    ),
                  ))
            ],
          ),
          Divider(),
          // _showMore(index)
        ],
      ),
      onTap: (){
        Navigator.pushNamed(context, Constants.PRODUCTCONTENT,
            arguments: {
              "id":"${value[index].id}"
            });
      },
    );
  }

  //顶部导航栏
  Widget _productTopWidget() {
    return Positioned(
        top: 0,
        height: ScreenAdapter.height(80),
        width: ScreenAdapter.width(750),
        child: Container(
          width: ScreenAdapter.width(750),
          height: ScreenAdapter.height(80),
          decoration: BoxDecoration(
              border: Border(
                  bottom: BorderSide(
                      width: ScreenAdapter.width(1),
                      color: Color.fromRGBO(233, 233, 233, 0.9)))),
          child: Row(
            children: subHeaderList.map((value) {
              return Expanded(
                child: InkWell(
                  child: Padding(
                    padding: EdgeInsets.fromLTRB(
                        0, ScreenAdapter.width(16), 0, ScreenAdapter.width(16)),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: <Widget>[
                        Text(
                          "${value["title"]}",
                          textAlign: TextAlign.center,
                          style: TextStyle(
                              color: (this._selectHeaderId == value["id"])
                                  ? Colors.red
                                  : Colors.black54),
                        ),
                        _showIcon(value["id"]),
                      ],
                    ),
                  ),
                  onTap: () {
                    _subHeaderChange(value["id"]);
                  },
                ),
                flex: 1,
              );
            }).toList(),
          ),
        ));
  }

  //显示header icon
  Widget _showIcon(id) {
    if (id == 2) {
      if (isSalesDown) {
        if (subHeaderList[id - 1]["sort"] == -1) {
          isSalesDown = true;
        } else {
          isSalesDown = false;
        }
      }

      return GestureDetector(
        child: Icon(
          (isSalesDown ? Icons.arrow_drop_down : Icons.arrow_drop_up),
          color: (this._selectHeaderId == id) ? Colors.red : Colors.black54,
        ),
        onTap: () {
          setState(() {
            if (isSalesDown) {
              isSalesDown = false;
            } else {
              isSalesDown = true;
            }
            _changeOrder(id, isSalesDown);
          });
        },
      );
    } else if (id == 3) {
      if (isPriceDown) {
        if (subHeaderList[id - 1]["sort"] == -1) {
          isPriceDown = true;
        } else {
          isPriceDown = false;
        }
      }
      return GestureDetector(
        child: Icon(
          (isPriceDown ? Icons.arrow_drop_down : Icons.arrow_drop_up),
          color: (this._selectHeaderId == id) ? Colors.red : Colors.black54,
        ),
        onTap: () {
          if (isPriceDown) {
            isPriceDown = false;
          } else {
            isPriceDown = true;
          }
          _changeOrder(id, isPriceDown);
        },
      );
    } else {
      return Text("");
    }
  }

  //修改升序降序
  _changeOrder(id, bool isDown) {
    setState(() {
      this._selectHeaderId = id;
      //用于上拉分页
      this._scrollController = ScrollController(); //listview 的控制器
      this._refreshController = RefreshController(initialRefresh: false);
      if (isDown) {
        this._sort =
            "${subHeaderList[id - 1]["fileds"]}_${subHeaderList[id - 1]["sort"]}";
      } else {
        this._sort =
            "${subHeaderList[id - 1]["fileds"]}_${-subHeaderList[id - 1]["sort"]}";
      }

      //请求数据
      this._loadData(true);
    });
  }

  //导航改变
  _subHeaderChange(id) {
    if (id == 4) {
      _scaffoldKey.currentState.openEndDrawer();
      setState(() {
        this._selectHeaderId = id;
      });
    } else {
      setState(() {
        this._selectHeaderId = id;
        //用于上拉分页
        this._scrollController = ScrollController(); //listview 的控制器
        this._refreshController = RefreshController(initialRefresh: false);
        if(id == 2){
          if(isSalesDown){
            this._sort =
            "${subHeaderList[id - 1]["fileds"]}_${subHeaderList[id - 1]["sort"]}";
          }else{
            this._sort =
            "${subHeaderList[id - 1]["fileds"]}_${-subHeaderList[id - 1]["sort"]}";
          }
        }else if(id == 3){
          if(isPriceDown){
            this._sort =
            "${subHeaderList[id - 1]["fileds"]}_${subHeaderList[id - 1]["sort"]}";
          }else{
            this._sort =
            "${subHeaderList[id - 1]["fileds"]}_${-subHeaderList[id - 1]["sort"]}";
          }
        }else{
          this._sort =
          "${subHeaderList[id - 1]["fileds"]}_${subHeaderList[id - 1]["sort"]}";
        }

        //请求数据
        this._loadData(true);
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    ScreenAdapter.init(context);

    return Scaffold(
      key: _scaffoldKey,
      appBar: _isShowSearchAppBar?AppBar(
        elevation: 0,
        title: Container(
          height: ScreenAdapter.height(68),
          padding: EdgeInsets.fromLTRB(ScreenAdapter.width(30), 0, ScreenAdapter.width(30), 0),
          child: Row(
            children: [
              Icon(
                Icons.search,
                color: Colors.black38,
                size: 20,
              ),
              SizedBox(
                width: ScreenAdapter.width(15),
              ),
              Expanded(
                child:  TextField(
                  controller: _initKeywordsController,
                  decoration: InputDecoration(
                    focusedBorder: OutlineInputBorder(
                        borderSide:
                        BorderSide(width: 0, color: Colors.transparent)),
                    disabledBorder: OutlineInputBorder(
                        borderSide:
                        BorderSide(width: 0, color: Colors.transparent)),
                    enabledBorder: OutlineInputBorder(
                        borderSide:
                        BorderSide(width: 0, color: Colors.transparent)),
                    border: OutlineInputBorder(
                        borderSide:
                        BorderSide(width: 0, color: Colors.transparent)),
                    contentPadding: EdgeInsets.symmetric(vertical: 0),
                  ),
                  onChanged: (value){
                    this._keyWords = value;
                  },
                ),
              ),
            ],
          ),
          decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(30), color: Color.fromRGBO(233, 233, 233, 0.8)),
        ),
        actions: [
          Container(
            margin: EdgeInsets.only(right: ScreenAdapter.width(20)),
            child:Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                GestureDetector(
                  child: Text("搜索"),
                  onTap: (){
                    if(this._keyWords==null||this._keyWords.isEmpty){
                      print("请输入商品名称");
                    }else{
                      SearchServices.setHistoryData( this._keyWords);
                      widget.arguments['keyWords'] = this._keyWords;
                      _loadData(true);
                    }
                  },
                ),
              ],
            ),
          ),
        ],
      ):
      AppBar(
        elevation: 0,
        title: Text("${widget.arguments['title']}"),
        actions: <Widget>[Text("")],
        leading: IconButton(
          icon: Icon(Icons.arrow_back_rounded),
          onPressed: () {
            Navigator.of(context).pop();
          },
        ),
      ),
      endDrawer: Drawer(
        child: Center(
          child: Text("筛选功能"),
        ),
      ),
      // body: Text("Product:${widget.arguments}"),
      body: Stack(
        children: <Widget>[
          _productListWidget(this._productList),
          _productTopWidget(),
        ],
      ),
    );
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
  }
}
